﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using ProjectBase.Core;

using Survey.Common;
using Survey.Common.Validation;

namespace Survey.Business
{
    public abstract class EntityValidatorBase<TEntity, TID, TDao> : ValidatorBase<TEntity>, IEntityValidator<TEntity>
        where TEntity : class, IPersistentObjectWithTypedId<TID>
        where TDao : class, IReadDao<TEntity, TID>
    {
        public virtual TDao Dao { protected get; set; }

        public virtual bool CanBeDeleted(TEntity entity)
        {
            // no item, no validation
            if (entity.IsNull())
            {
                return false;
            }

            var result = true;

            foreach (var rule in Rules.Select(ValidateOn.CanDelete, ApplyOn.Server))
            {
                ValidationMessage message;
                if (rule.Validate(entity, out message).Equals(ValidationResult.IsValid))
                {
                    continue; // OK
                }

                result = false; // Error
                if (rule.BreakOnError)
                {
                    break;
                }
            }
            return result;
        }
        public virtual bool CanBeEdited(TEntity entity)
        {
            // no item, no validation
            if (entity.IsNull())
            {
                return false;
            }

            var result = true;

            foreach (var rule in Rules.Select(ValidateOn.CanEdit, ApplyOn.Server))
            {
                ValidationMessage message;
                if (rule.Validate(entity, out message).Equals(ValidationResult.IsValid))
                {
                    continue; // OK
                }

                result = false; // Error
                if (rule.BreakOnError)
                {
                    break;
                }
            }
            return result;
        }
    }
}